package ch1200;

public class ThreadProgram {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		//摆出一个饭局线程
        HaveLunch haveLunch=new HaveLunch();
        //创建3个能吃饭的线程对象,You,I,He，新建状态
        Thread you=new Thread(haveLunch,"You");
        Thread i=new Thread(haveLunch,"I");
        Thread he=new Thread(haveLunch,"He");
        //运行You,I,He，让他们能抢占cpu,并发执行，start启动并不意味着线程立即执行，就绪状态，
        //谁来使用cpu，是操作系统的调度算法说了算
        you.start();
        i.start();
        he.start();
        //测试idea的git
	}

}

//定义“吃饭”的线程，implements Runnable说明了这个类是线程
class HaveLunch implements Runnable{
	private int rice=100;

	@Override  //覆写
	public void run() {
		// TODO 自动生成的方法存根
		//一直吃,dirty read,脏读写
		while (!Thread.currentThread().isInterrupted()) {
			//同步锁
			synchronized (this) {
				if (rice == 0)
					break;
				// 谁吃了第几颗米饭,Thread.currentThread().getName()可以取出当前抢占cpu的线程名
				System.out.println(Thread.currentThread().getName() + " have eaten No." + rice-- + " Rice ");
				
			}
			//当前线程稍作休息，ms，休眠状态
			try {
				Thread.sleep(200);
				Thread.currentThread().interrupt();
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}

		}
	}

	
	
}
